package org.iartisan.thought.web.filter;


import org.apache.shiro.authz.AuthorizationException;
import org.iartisan.runtime.web.annotation.Auth;
import org.iartisan.runtime.web.authentication.RealmBean;
import org.iartisan.runtime.web.contants.WebConstants;
import org.iartisan.runtime.web.utils.WebUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *
 * @author King
 * @since 2018/4/3
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    /**
     * 此方法需要重写
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Auth annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Auth.class);
        } else {
            return true;
        }
        if (annotation != null) {
            //验证用户有没有登录
            RealmBean realmBean = (RealmBean) WebUtil.getShiroSession().getAttribute(WebConstants._USER);
            if (null == realmBean) {
                throw new AuthorizationException("请先登录");
            }
        }

        return true;
    }
}